package com.yixing.tech.wms.statistics.stream;

import com.yixing.tech.wms.statistics.service.IInventoryDataService;
import com.yixing.tech.wms.statistics.service.IInventoryStatisticsService;
import com.yixing.tech.wms.stock.out.domain.Inventory;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.data.mongodb.core.messaging.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class InventoryInfoListener implements MessageListener<ChangeStreamDocument<Document>, Inventory> {

    @Resource
    IInventoryStatisticsService inventoryStatisticsService;

    @Resource
    IInventoryDataService inventoryDataService;

    @Override
    public void onMessage(Message<ChangeStreamDocument<Document>, Inventory> message) {
        OperationType operationType = message.getRaw().getOperationType();
        log.error("操作类型:{}", operationType);
        log.error("变更数据主体:{}", message.getBody());

        if(OperationType.INSERT.equals(operationType)) {
            inventoryStatisticsService.insertInventory(message.getBody());
            inventoryDataService.insertInventoryIntoMesTable(message.getBody());

        }else if(OperationType.UPDATE.equals(operationType)) {
            inventoryStatisticsService.updateInventory(message.getBody());
            inventoryDataService.updateInventoryMesTable(message.getBody());

        }else if(OperationType.DELETE.equals(operationType)) {
            inventoryStatisticsService.removeInventory(message.getBody());
        }
    }
}
